package com.daxia.bumall.web.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daxia.bumall.common.ProductSellingStatus;
import com.daxia.bumall.common.ProductStatus;
import com.daxia.bumall.dto.DesignDTO;
import com.daxia.bumall.dto.DesignProductDTO;
import com.daxia.bumall.util.MyWebUtils;

@Controller
@RequestMapping(value = "buy", produces="text/html;charset=UTF-8")
public class BuyController extends BaseController {

	/**
	 * 从三维家“一键购买”跳过来的
	 * @param SchemeId 通过这个去查找design，然后找designproduct
	 * @param map
	 * @return
	 */
	@Transactional
    @RequestMapping(value = "/fromPlan")
    public String fromPlan(String SchemeId, Map<String, Object> map) {
    	assertTrue(StringUtils.isNotBlank(SchemeId), "planId不能为空");
    	if (getCurrentUserDTO() == null) {
    		// 没有登陆
    		MyWebUtils.getCurrentRequest().getSession().setAttribute("planId", SchemeId);
    		return "redirect:/user/login";
    	}
    	MyWebUtils.getCurrentRequest().getSession().removeAttribute("planId");
    	
    	DesignDTO design = designService.findByPlanId(SchemeId);
    	//assertTrue(design != null, "方案找不到对应的方案");
    	if (design != null) {
	    	List<DesignProductDTO> designProducts = designProductService.findByDesign(design.getId());
	    	for (DesignProductDTO dp : designProducts) {
	    		if (dp.getSpecification().getProduct().getSellingStatus() == null || dp.getSpecification().getProduct().getSellingStatus() != ProductSellingStatus.OnSell.getValue()) {
					logger.error("产品已下架【" + dp.getSpecification().getOgCode() + "】");
					continue;
				}
	    		if(dp.getSpecification().getProduct().getStatus()==null||dp.getSpecification().getProduct().getStatus()!=ProductStatus.Passed.getValue()){
	    			logger.error("产品未通过审核【" + dp.getSpecification().getOgCode() + "】");
					continue;
	    		}
				cartService.addToCart(dp.getSpecification().getProduct().getId(), dp.getCount(), dp.getSpecification().getId());
			}
    	}
    	
    	return "redirect:/cart/cartList";
	}
	
}	